#include "WidgetList.h"
#include "RessourceManager.h"
#include <iostream>

WidgetList::WidgetList(int x, int y, int w, int h, int textSize) : Widget(x,y)
{
    this->w = w;
    this->h = h;
    this->textSize = textSize;
    box.setSize(sf::Vector2f(w,h));
    box.setPosition(x,y);
    box.setFillColor(sf::Color(0,0,0,100));
    selector = -1;
    offset = 0;
    graphicalText = new sf::Text[h/textSize];
    for(int i=0; i<h/textSize;i++)
    {
        graphicalText[i].setPosition(x+3, y+textSize*i);
        graphicalText[i].setCharacterSize(textSize*4/5);
        graphicalText[i].setColor(sf::Color(255,255,255,255));
        graphicalText[i].setFont(*RessourceManager::getFont("font.ttf"));
    }
    selection.setFillColor(sf::Color(120,120,120,255));
    selection.setSize(sf::Vector2f(w, textSize));

}

void WidgetList::onRender(sf::RenderWindow* window)
{
    window->draw(box);

    if(selector != -1)
        window->draw(selection);

    for(int i=0; i<h/textSize;i++)
    {
        window->draw(graphicalText[i]);
    }

}

void WidgetList::onEvent(sf::Event* event)
{
    if(event->type == sf::Event::MouseButtonPressed && event->mouseButton.button == sf::Mouse::Button::Left)
    {
        int mX = event->mouseButton.x;
        int mY = event->mouseButton.y;
        if(mX > x && mX < x+w && mY > y && mY < y+h)
        {
            int num = (mY - y) / textSize;
            if(num < text.size())
            {
                select(num);
            }
            else
            {
                select(-1);
            }
        }
    }
}

void WidgetList::select(int i)
{
    selector = i;
    updateGfx();
}

void WidgetList::updateGfx()
{
    selection.setPosition(x, y+(selector-offset)*textSize);
    for(int i=0; i<h/textSize;i++)
    {
        if(text.size() > i+offset)
        {
            graphicalText[i+offset].setString(text[i+offset]);
        }
        else
        {
            graphicalText[i+offset].setString("");
        }

    }
}

void WidgetList::add(std::string s)
{
    text.push_back(s);
    updateGfx();
}

void WidgetList::clear()
{
    text.clear();
    updateGfx();
}

std::string* WidgetList::getSelected()
{
    return (selector == -1 ? NULL : &text[selector]);
}

WidgetList::~WidgetList()
{
    //dtor
}
